<template>
  <div class="baseInfo">
    <div class="baseInfo-header" v-if="rtStatus=='PREPARE'">
      <el-button type="primary" size="small" @click="handleAdd">新增</el-button>
      <el-button type="danger" size="small" @click="handleDelete">删除</el-button>
    </div>
    <vxe-table
      border
      stripe
      ref="tableRef"
      size="small"
      header-align="center"
      :row-config="rowConfig"
      :column-config="columnConfig"
      :data="tableData"
      @checkbox-change="checkboxChangeEvent"
      @checkbox-all="checkboxAll"
    >
      <vxe-column type="checkbox" width="40" fixed="left"></vxe-column>
      <vxe-column type="seq" width="70" align="center" fixed="left"></vxe-column>
      <vxe-column field="itemCode" width="120" show-overflow="title" align="center" title="产品代码"></vxe-column>
      <vxe-column field="itemName" width="120" show-overflow="title" align="center" title="产品名称"></vxe-column>
      <vxe-column field="specification" width="80" show-overflow="title" align="center" title="规格"></vxe-column>
      <vxe-column field="batchCode" width="80" show-overflow="title" align="center" title="批次"></vxe-column>
      <vxe-column field="warehouseCode" show-overflow="title" width="120" align="center" title="仓库代码"></vxe-column>
      <vxe-column field="warehouseName" show-overflow="title" width="120" align="center" title="仓库名称"></vxe-column>
      <vxe-column field="locationName" width="80" show-overflow="title" align="center" title="库区"></vxe-column>
      <vxe-column field="areaName" width="80" show-overflow="title" align="center" title="库位"></vxe-column>
      <vxe-column field="unitOfMeasure" width="120" show-overflow="title" align="center" title="单位名称"></vxe-column>
      <vxe-column field="quantityCurr" width="120" show-overflow="title" align="center" title="现有库存"></vxe-column>
      <vxe-column field="quantityRted" show-overflow="title" width="120" align="center" title="退货数量"></vxe-column>
      <vxe-column field="price" width="120" show-overflow="title" align="center" title="单价(含税)"></vxe-column>
      <vxe-column field="totalPrice" width="120" show-overflow="title" align="center" title="总价(含税)"></vxe-column>
      <vxe-column field="priceExTax" width="120" show-overflow="title" align="center" title="单价(不含税)"></vxe-column>
      <vxe-column field="totalPriceExTax" width="120" show-overflow="title" align="center" title="总价(不含税)"></vxe-column>
      <vxe-column field="remark" width="120" show-overflow="title" align="center" title="备注"></vxe-column>
      <vxe-column width="160" align="center" title="操作" fixed="right" v-if="rtStatus=='PREPARE'">
        <template #default="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </vxe-column>
    </vxe-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="1200px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8" v-if="detailPurchaseList.length">
            <el-form-item label="产品(物料名称)" prop="itemId">
              <el-select v-model="form.itemId" placeholder="请选择产品(物料名称)" @change="handleChange">
                <el-option
                  v-for="dict in detailPurchaseList"
                  :key="dict.productId"
                  :label="dict.productName"
                  :value="dict.productId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-else>
            <el-form-item label="产品(物料名称)" prop="itemName">
              <el-input v-model="form.itemName" readonly placeholder="请选择产品(物料名称)" >
                <el-button slot="append" @click="handleSelectProduct" icon="el-icon-search"></el-button>
              </el-input>
              <ItemSelect ref="itemSelect" v-if="showItemSelect" @onSelected="onItemSelected" @closeSelect="showItemSelect=false"> </ItemSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="批次号" prop="batchCode">
              <el-input v-model="form.batchCode" disabled placeholder="请输入批次号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品(物料编号)" prop="itemCode">
              <el-input v-model="form.itemCode" disabled placeholder="请输入产品(物料编号)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="form.specification" disabled="" placeholder="请输入规格" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unitOfMeasure">
              <el-input v-model="form.unitOfMeasure" disabled placeholder="请输入单位名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货仓库">
              <el-cascader v-model="warehouseInfo"
                :options="warehouseOptions"
                :props="warehouseProps"
                @change="handleWarehouseChanged"
                placeholder="请选择仓库/库区"
                style="width: 240px"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="退货数量" prop="quantityRted">
              <el-input-number v-model="form.quantityRted" controls-position="right" :min="0" @change="calculatePrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(含税)" prop="price">
              <el-input-number v-model="form.price" controls-position="right" :min="0" @change="calculatePrice"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折扣" prop="discount">
              <el-input-number v-model="form.discount" controls-position="right" :min="0" :max="1" :precision="2" :step="0.01" @change="calculatePrice"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="总价(含税)" prop="totalPrice">
              <el-input-number v-model="form.totalPrice" controls-position="right" :min="0" disabled></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单价(不含税)" prop="priceExTax">
              <el-input-number v-model="form.priceExTax" controls-position="right" :min="0" @change="calculatePriceExTax"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价(不含税)" prop="totalPriceExTax">
              <el-input-number v-model="form.totalPriceExTax" controls-position="right" :min="0" disabled></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="单价(不含税)" prop="priceExTax">
              <el-input-number v-model="form.priceExTax" controls-position="right" :min="0" ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="总价(不含税)" prop="totalPriceExTax">
              <el-input-number v-model="form.totalPriceExTax" controls-position="right" :min="0" ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ItemSelect  from "@/components/itemSelect/single.vue";
import { detailPurchaseOrder } from "@/api/mes/pro/purchaseOrder";
import { listRtvendorline } from "@/api/mes/wm/rtvendorline";
import { getTreeList } from "@/api/mes/wm/warehouse"
import { addRtvendorline, updateRtvendorline, delRtvendorline } from "@/api/mes/wm/rtvendorline";
export default {
  name: 'baseInfo',
  props: {
    rtId: undefined,
    poId: undefined,
    rtStatus: undefined,
  },
  components: {
    ItemSelect,
  },
  data() {
    return {
      showItemSelect: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      form: {},
      warehouseInfo: [],
      warehouseProps: {
        multiple: false,
        value: 'pId',
        label: 'pName',
        // 只选择到库区，不扩展至库位
        checkStrictly: true,
        lazy: false,
        expandTrigger: 'hover'
      },
      tableData: [],
      columnConfig: {
        drag: true,
        resizable: true,
        storage: true,
        sortConfig: {
          trigger: 'cell',
          remote: true
        },
        align: 'center',
        headerAlign: 'center'
      },
      rowConfig: {
        drag: true,
        keyField: 'id',
        isHover: true,
      },
      total: 0,
      title: '',
      open: false,
      rules: {
        itemId: [
          { required: true, message: '请选择产品/物料', trigger: 'change' }
        ],
        itemCode: [
          { required: false, message: '请输入物料编码', trigger: 'blur' }
        ],
        itemName: [
          { required: true, message: '请输入产品(物料名称)', trigger: 'blur' }
        ],
        quantityRted: [
          { required: true, message: '请输入退货数量', trigger: 'blur' }
        ],
        productName: [
          { required: true, message: '请输入产品(物料名称)', trigger: 'blur' }
        ],
      },
      ids: [],
      detailPurchaseList: [], // 采购单下面的物料明细list
      warehouseOptions:[],
    }
  },
  created() {
    // this.getList();
    // console.log(this.rtId,'cellId');
    this.getWarehouseList()
  },
  watch: {
    rtId: {
      handler(val) {
        this.getList();
      },
    }
  },
  methods: {
    getWarehouseList(){
      // 获取树结构，供两级级联使用（仓库 -> 库区），不过滤到库位
      getTreeList().then(response => {        
        if(response.data && response.data.length > 0){
          // 过滤掉虚拟仓库
          this.warehouseOptions = response.data.filter((el) => {
            return el.warehouseCode && el.warehouseCode.indexOf('VIR') === -1;
          });
          // children 第一层为库区，去除更下层库位并转换字段
          this.warehouseOptions.forEach(w => {
            if (w.children && w.children.length > 0) {
              w.children.forEach(l => {
                // 去除库位层，保留到库区
                if (l.children) delete l.children;
              });
              let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');  
              w.children = JSON.parse(wstr); 
            }
          });
          let ostr = JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
          this.warehouseOptions = JSON.parse(ostr);
        } else {
          this.warehouseOptions = [];
        }
      });
    },
    /** 查询供应商退货行列表 */
    getList() {
      this.tableData = [];
      listRtvendorline({...this.queryParams, rtId: this.rtId}).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
        console.log('response', response);
      });
      if(this.poId){
        detailPurchaseOrder(this.poId, {pageNum: 1, pageSize: 999}).then(response => {
          this.detailPurchaseList = response.rows;
        })
      }else{
        this.detailPurchaseList = [];
      }
      // this.$emit('getBaseInfoList', this.queryParams)
    },
    reset(){
      this.form = {
        lineId: undefined,
        rtId: this.rtId,
        itemId: undefined,
        itemName: undefined,
        batchCode: undefined,
        itemCode: undefined,
        specification: undefined,
        unitOfMeasure: undefined,
        warehouseCode: undefined,
        quantityRted: undefined,
        price: undefined,
        totalPrice: undefined,
        priceExTax: undefined,
        totalPriceExTax: undefined,
        discount: 1.0,
        taxRate: 0.13,
        remark: undefined,
        warehouseId: undefined,
        locationId: undefined,
        areaId: undefined,
      };
      this.resetForm('form');
      this.warehouseInfo = [];
    },
    handleAdd(){
      this.title = '新增采购退货订单明细';
      this.open = true;
      this.reset()
      console.log('handleAdd');
    },
    handleEdit(row){
      this.title = '修改采购退货订单明细';
      this.open = true;
      this.form = {...row};
      this.warehouseInfo = [this.form.warehouseId, this.form.locationId];
    },
    checkboxChangeEvent(checked){
      this.ids = checked.records.map(item => item.lineId)
      console.log(checked.records, this.ids);
    },
    checkboxAll(checked){
      this.ids = checked.records.map(item => item.lineId)
      console.log(checked.records, this.ids)
    },
    handleDelete(row){
      const ids = row.lineId || this.ids;
      this.$confirm('确定要删除该条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRtvendorline(ids).then(response => {
          this.$message.success('删除成功')
          this.getList()
          // 更新总价到父组件
          this.updateTotalPriceToParent();
        })
      })
      console.log('handleDelete');
    },
    cancel(){
      this.open = false;
      this.reset();
      console.log('cancel');
    },
    submitForm(){
      console.log('submitForm', this.form);
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if(this.form.lineId){
            updateRtvendorline(this.form).then(response => {
              this.$message.success('修改成功')
              this.getList()
              this.cancel()
              // 更新总价到父组件
              this.updateTotalPriceToParent();
            })
          }else{
            addRtvendorline(this.form).then(response => {
              this.$message.success('新增成功')
              this.getList()
              this.cancel()
              // 更新总价到父组件
              this.updateTotalPriceToParent();
            })
          }
        }
      })
      console.log('submitForm');
    },
    //物料选择弹出框
    onItemSelected(obj){
      if(obj != undefined && obj != null){
        this.form.itemId = obj.itemId;
        this.form.itemCode = obj.itemCode;
        this.form.itemName = obj.itemName;
        this.form.batchCode = obj.batchCode;
        this.form.specification = obj.specification;
        this.form.unitOfMeasure = obj.unitOfMeasure;
        // 设置默认价格和税率
        this.form.price = obj.price || 0;
        this.form.priceExTax = obj.priceExTax || 0;
        this.form.taxRate = obj.taxRate || 0.13;
        this.form.discount = 1.0;
        // 自动计算价格
        this.calculatePrice();
      }
    },
    handleSelectProduct(){
      this.showItemSelect = true;
      this.$nextTick(()=>{
        this.$refs.itemSelect.showFlag = true;
      })
    },
    handleChange(val){
      this.detailPurchaseList.forEach(item => {
        if(item.productId == val){
          this.form.itemCode = item.productCode;
          this.form.itemName = item.productName;
          this.form.batchCode = item.batchCode;
          this.form.specification = item.productSpc;
          this.form.unitOfMeasure = item.unitOfMeasure;
          this.form.price = item.price || 0;
          this.form.priceExTax = item.priceExTax || 0;
          this.form.taxRate = item.taxRate || 0.13;
          // 自动计算价格
          this.calculatePrice();
        }
      })
    },
    // 选择退货仓库（两级：仓库/库区），不扩展至库位
    handleWarehouseChanged(obj){
      if (obj && obj.length) {
        this.form.warehouseId = obj[0];
        this.form.locationId = obj[1];
        this.form.areaId = undefined;
        // 名称填充
        try {
          const warehouse = this.warehouseOptions.find(w => w.pId === obj[0]);
          this.form.warehouseName = warehouse ? warehouse.pName : undefined;
          if (warehouse && warehouse.children) {
            const location = warehouse.children.find(l => l.pId === obj[1]);
            this.form.locationName = location ? location.pName : undefined;
          }
        } catch(e) {}
      }
    },
    // 计算含税总价：单价（含税）*数量*折扣
    calculatePrice() {
      const price = Number(this.form.price) || 0;
      const qty = Number(this.form.quantityRted) || 0;
      const discount = Number(this.form.discount) || 0;
      this.form.totalPrice = Number((price * qty * discount).toFixed(2));
      // 同时计算不含税总价
      this.calculatePriceExTax();
    },
    // 计算不含税总价：单价（不含税）*数量*折扣/税率
    calculatePriceExTax() {
      const priceExTax = Number(this.form.priceExTax) || 0;
      const qty = Number(this.form.quantityRted) || 0;
      const discount = Number(this.form.discount) || 0;
      const taxRate = Number(this.form.taxRate);
      if (priceExTax && qty && discount && taxRate) {
        this.form.totalPriceExTax = Number(((priceExTax * qty * discount) / taxRate).toFixed(2));
      } else {
        this.form.totalPriceExTax = 0;
      }
    },
    // 计算不含税单价：含税单价 / (1 + 税率)
    calculatePriceExTaxFromPrice() {
      if (this.form.price && this.form.taxRate) {
        this.form.priceExTax = this.form.price / (1 + this.form.taxRate);
        this.calculatePriceExTax();
      }
    },
    // 计算含税单价：不含税单价 * (1 + 税率)
    calculatePriceFromPriceExTax() {
      if (this.form.priceExTax && this.form.taxRate) {
        this.form.price = this.form.priceExTax * (1 + this.form.taxRate);
        this.calculatePrice();
      }
    },
    // 更新总价到父组件
    updateTotalPriceToParent() {
      const totalPrice = this.tableData.reduce((sum, item) => sum + (item.totalPrice || 0), 0);
      const totalPriceExTax = this.tableData.reduce((sum, item) => sum + (item.totalPriceExTax || 0), 0);
      this.$emit('updateTotalPrice', totalPrice, totalPriceExTax);
    },
    // 设置采购订单物料明细
    setPurchaseOrderLines(lines) {
      this.detailPurchaseList = lines;
      console.log('设置采购订单物料明细:', lines);
    }
  }
}
</script>

<style lang="scss" scoped>
.baseInfo{
  &-header{
    margin-bottom: 10px;
  }
}
</style>